Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
date-fns | format date

Problem

I have below function that formats date string.

import { format, parseISO } from "date-fns";

export function convertDate(myDate, displayFormat) {
    return format(new Date(parseISO(myDate)), displayFormat);
}

I have articles that has content such as

title: 'My title'
date: '2022-01-04'

I call the convertDate function using below:

if (articles) {
        for (let i = 0; i < articles.length; i++) {
            const year = convertDate(articles[i].date, "y");
            years.push(year);
        }
        uniqueYear = [...new Set(years)];
    }

My timezone is CEST.

Error

I am getting error: Error

Expected result:

Result

I can call the function by using {convertDate(article.date, "PPP")} which also works.

Please help!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Running the following minimal example at runkit.com returns "2022", it doesn't throw the error described in the OP:

var dateFns = require("date-fns")

function convertDate(myDate, displayFormat) {
    return dateFns.format(new Date(dateFns.parseISO(myDate)), displayFormat);
}

let articles = [{
  title: 'My title',
  date: '2022-01-04'
}];

convertDate(articles[0].date, "y"); // "2022"

So the error is elsewhere.

Also, the use of new Date is redundant:

dateFns.format(dateFns.parseISO(myDate), displayFormat)

is sufficient and more robust.

As suggested elsewhere, getting the year from the timestamp can be done using string manipulation, no need for casting to a Date. To get the years:

let articles = [{title: 'title 0', date: '2022-01-04'},
                {title: 'title 1', date: '2020-01-04'}];

let years = articles.map(o => o.date.substring(0,4));

console.log(years);

If you need it as a Date for other things (e.g. formatted month name), cast it to a Date once and reuse it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda